package com.ybkj.o2o.sales.manager.impl;

import com.ybkj.o2o.sales.common.DataGrid;
import com.ybkj.o2o.sales.entity.Activity;
import com.ybkj.o2o.sales.entity.ActivityCouponRule;
import com.ybkj.o2o.sales.entity.Coupon;
import com.ybkj.o2o.sales.entity.CouponRule;
import com.ybkj.o2o.sales.manager.CouponManager;
import com.ybkj.o2o.sales.service.ActivityCouponRuleService;
import com.ybkj.o2o.sales.service.ActivityService;
import com.ybkj.o2o.sales.service.CouponRuleService;
import com.ybkj.o2o.sales.service.CouponService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class DefaultCouponManager implements CouponManager {

    @Autowired
    private CouponService couponService;
    @Autowired
    private CouponRuleService couponRuleService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ActivityCouponRuleService activityCouponRuleService;

    @Override
    public Integer couponTimes(Long couponRuleId, String phone, Long passengerId) {
        Integer times = couponService.couponTimes(couponRuleId, phone, passengerId);
        return times;
    }

    @Override
    public Coupon findOneCoupon(String appKey, Long couponRuleId) {
        Coupon coupon = couponService.findOneCoupon(appKey, couponRuleId);
        return coupon;
    }


    @Override
    public Coupon findOne(Long id, String appKey) {

        Coupon coupon = couponService.findOne(id, appKey);

        if (null != coupon) {
            coupon.setCouponRule(couponRuleService.findOne(coupon.getCouponRuleId(), appKey));
        }

        return coupon;
    }

    @Override
    public Coupon findOneByCode(String couponCode, String appKey) {

        Coupon coupon = couponService.findOneByCode(couponCode, appKey);

        if (null != coupon) {
            coupon.setCouponRule(couponRuleService.findOne(coupon.getCouponRuleId(), appKey));
        }

        return coupon;
    }

    /**
     * 事务回滚.
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(Coupon coupon) {

        couponService.update(coupon);

    }


    @Override
    public List<Coupon> findAll(Long ruleId, String appKey) {
        return couponService.findAll(ruleId, appKey);
    }

    @Transactional(rollbackFor = Exception.class)
    public void mass(Long couponRuleId, Integer amount, String appKey) {
        CouponRule couponRule = couponRuleService.findOne(couponRuleId, appKey);
        couponService.mass(couponRule, amount, appKey);
    }
//  @Transactional(rollbackFor = Exception.class)
//  public void mass(CouponRule couponRule, Integer amount, String appKey, Long lineId, BigDecimal linePrice, Double couponDiscount, String lineName) {
//
//    couponService.mass(couponRule, amount, appKey, lineId, linePrice, couponDiscount, lineName);
//  }

    /**
     * 事务回滚.
     */
    @Transactional(rollbackFor = Exception.class)
    public void giftCoupon(String passengerIds, String couponRuleId, String amount, String phone,
                           String appKey) {

        couponService.giftCoupon(passengerIds, couponRuleId, amount, phone, appKey);

    }

    /**
     * 事务回滚.
     */
    @Transactional(rollbackFor = Exception.class)
    public void invalid(Long id, String appKey) {

        Coupon coupon = couponService.findOne(id, appKey);
        coupon.setStatus(Coupon.COUPON_STATUS_INVALID);
        couponService.update(coupon);

    }

    @Override
    public DataGrid<Coupon> findCoupon(Long ruleId, String code, String phone, Integer page,
                                       Integer rows, String appKey) {

        Integer offset = 0;
        if (page != null && rows != null) {
            offset = (page - 1) * rows;
        }

        String likeCode = null;

        String likePhone = null;

        if (StringUtils.isNotBlank(code)) {
            likeCode = "%" + code + "%";
        }
        if (StringUtils.isNotBlank(phone)) {
            likePhone = "%" + phone + "%";
        }

        List<Coupon> list = couponService.selectByRuleWithParams(ruleId, likeCode, likePhone, offset, rows, appKey);
        long count = couponService.countByRuleWithParams(ruleId, likeCode, likePhone, appKey);

        DataGrid<Coupon> dataGrid = new DataGrid<Coupon>();
        dataGrid.setRows(list);
        dataGrid.setTotal(count);

        return dataGrid;
    }

    @Override
    public List<Coupon> listValidByPassenger(Long passengerId, String couponType, Long couponTypeId, String appKey, Long[] linesId) {
        List<Long> lineIdList = new ArrayList<>();
        if (null != linesId && linesId.length > 0) {
            for (int i = 0; i < linesId.length; i++) {
                lineIdList.add(linesId[i]);
            }
        }
        List<Coupon> coupons = couponService.listValidByPassenger(passengerId, appKey);
        List<Coupon> newCoupons = new ArrayList<Coupon>();
        if (!CollectionUtils.isEmpty(coupons)) {
            for (Coupon coupon : coupons) {
                //获取优惠券规则
                CouponRule rule = couponRuleService.findOne(coupon.getCouponRuleId(), appKey);
                //获取规则和活动的额绑定关系
                List<ActivityCouponRule> acrList = activityCouponRuleService.listByCouponRule(rule.getId());
                //是否有活动开启
                boolean isAct = false;
                for(ActivityCouponRule acr : acrList){
                    Long activityId = acr.getActivityId();
                    Activity activity = activityService.findOne(activityId,appKey);
                    //活动是否有效
                    if(!activity.isStoped() && activity.getTimeStatus().equals(Activity.ACTIVITY_STATUS_ONUSING)){
                        //活动是否满足线路(0为所有线路)
                        if(lineIdList.contains(activity.getLineId()) || 0 == activity.getLineId()){
                            isAct = true;
                            break;
                        }
                    }
                }

                //获取规则绑定的活动信息
                if (!rule.isLapsed() && rule.getTimeStatus().equals(CouponRule.COUPONRULE_STATUS_ONUSING)) {
                    if (StringUtils.isBlank(couponType) || (rule.getCouponType().toString().equals(couponType))) {
                        if (isAct) {
                            if (null != couponTypeId) {
                                if (couponTypeId.equals(rule.getCouponTypeId())) {
                                    coupon.setCouponRule(rule);
                                    newCoupons.add(coupon);
                                }
                            } else {
                                coupon.setCouponRule(rule);
                                newCoupons.add(coupon);
                            }
                        }
                    }
                }
            }
        }
        return newCoupons;
    }

    @Override
    public DataGrid<Coupon> queryByPassenger(Long passengerId, Integer status, String couponType, Integer page, Integer rows, String appKey) {
        Integer offset = 0;
        if (page != null && rows != null) {
            offset = (page - 1) * rows;
        }

        List<Coupon> list = couponService.selectByPassenger(passengerId, status, couponType, offset, rows, appKey);
        long count = couponService.countByPassenger(passengerId, status, couponType, appKey);

        if (!CollectionUtils.isEmpty(list)) {
            for (Coupon coupon : list) {
                coupon.setCouponRule(couponRuleService.findOne(coupon.getCouponRuleId(), appKey));
            }
        }

        DataGrid<Coupon> dataGrid = new DataGrid<Coupon>();
        dataGrid.setRows(list);
        dataGrid.setTotal(count);

        return dataGrid;
    }

    /**
     * 事务回滚.
     */
    @Transactional(rollbackFor = Exception.class)
    public BigDecimal sumMoneyByPassenger(Long passengerId, String appKey) {
        BigDecimal money = new BigDecimal(0);
        List<Coupon> coupons = couponService.listValidByPassenger(passengerId, appKey);
        if (!CollectionUtils.isEmpty(coupons)) {
            for (Coupon coupon : coupons) {
                CouponRule rule = couponRuleService.findOne(coupon.getCouponRuleId(), appKey);
                if (!rule.isLapsed() && rule.getTimeStatus().equals(CouponRule.COUPONRULE_STATUS_ONUSING)) {
                    if (rule.getType().equals(CouponRule.TYPE_DEDUCTION)) {
                        money = money.add(rule.getMoney());
                    }
                }
            }
        }
        return money;
    }


    /**
     * 事务回滚.
     */
    @Transactional(rollbackFor = Exception.class)
    public Coupon insert(Long passengerId, String phone, Long couponRuleId, Integer status,
                         String code, Long runCode, String codeKey, String appKey) {

        Coupon coupon = new Coupon();
        coupon.setPassengerId(passengerId);
        coupon.setPhone(phone);
        coupon.setCouponRuleId(couponRuleId);
        coupon.setStatus(status);
        coupon.setCode(code);
        coupon.setRunCode(runCode);
        coupon.setCodeKey(codeKey);
        coupon.setAppKey(appKey);
        Long integer = couponService.insertRecord(coupon);
        if (integer != 1) {
            throw new RuntimeException("创建失败!!");
        }
        return coupon;
    }


}
